'use client'

import { useEffect, useRef, useState, ReactNode } from 'react'
import { ChartSkeleton, CardSkeleton, ListSkeleton } from './ui/skeleton'

interface LazyLoaderProps {
  children: ReactNode
  fallback?: ReactNode
  threshold?: number
  rootMargin?: string
  className?: string
}

// 通用懒加载组件
export function LazyLoader({
  children,
  fallback = <ChartSkeleton />,
  threshold = 0.1,
  rootMargin = '50px',
  className
}: LazyLoaderProps) {
  const [isVisible, setIsVisible] = useState(false)
  const [hasLoaded, setHasLoaded] = useState(false)
  const ref = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !hasLoaded) {
          setIsVisible(true)
          setHasLoaded(true)
          observer.disconnect()
        }
      },
      {
        threshold,
        rootMargin
      }
    )

    if (ref.current) {
      observer.observe(ref.current)
    }

    return () => observer.disconnect()
  }, [threshold, rootMargin, hasLoaded])

  return (
    <div ref={ref} className={className}>
      {isVisible ? children : fallback}
    </div>
  )
}

// 图表懒加载组件
export function LazyChart({ children, className }: { children: ReactNode; className?: string }) {
  return (
    <LazyLoader
      fallback={<ChartSkeleton className={className} />}
      className={className}
    >
      {children}
    </LazyLoader>
  )
}

// 卡片懒加载组件
export function LazyCard({ children, className }: { children: ReactNode; className?: string }) {
  return (
    <LazyLoader
      fallback={<CardSkeleton className={className} />}
      className={className}
    >
      {children}
    </LazyLoader>
  )
}

// 列表懒加载组件
export function LazyList({
  children,
  count = 5,
  className
}: {
  children: ReactNode;
  count?: number;
  className?: string
}) {
  return (
    <LazyLoader
      fallback={<ListSkeleton count={count} className={className} />}
      className={className}
    >
      {children}
    </LazyLoader>
  )
}

// 延迟加载组件（基于时间）
export function DelayedLoader({
  children,
  delay = 1000,
  fallback = <ChartSkeleton />
}: {
  children: ReactNode;
  delay?: number;
  fallback?: ReactNode
}) {
  const [isLoaded, setIsLoaded] = useState(false)

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoaded(true)
    }, delay)

    return () => clearTimeout(timer)
  }, [delay])

  return isLoaded ? <>{children}</> : <>{fallback}</>
}
